package com.example.denglu.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.UUID;

public class WeChatUtil {
    // 测试号信息，请替换为您的测试号信息
    private static final String APP_ID = "wx7afbe5c97a971d85";
    private static final String APP_SECRET = "378fd6130711b5cb2817b7c6cda90b7c";
    
    // 获取access_token的URL
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    
    // 获取二维码ticket的URL
    private static final String QRCODE_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s";
    
    // 通过ticket获取二维码的URL
    private static final String QRCODE_URL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s";
    
    // 获取用户信息的URL
    private static final String USER_INFO_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN";

    // 添加TOKEN常量
    private static final String TOKEN = "denglu123";

    // 回调URL
    private static final String CALLBACK_URL = "http://115.239.248.196:49503/denglu/wechatCallback";

    // 获取access_token
    public static String getAccessToken() throws IOException {
        String url = String.format(ACCESS_TOKEN_URL, APP_ID, APP_SECRET);
        String result = httpGet(url);
        JSONObject json = JSON.parseObject(result);
        return json.getString("access_token");
    }

    // 生成临时二维码
    public static JSONObject createTempQRCode(String sceneStr) throws IOException {
        String accessToken = getAccessToken();
        String url = String.format(QRCODE_TICKET_URL, accessToken);
        
        JSONObject data = new JSONObject();
        data.put("expire_seconds", 600); // 10分钟有效期
        data.put("action_name", "QR_STR_SCENE");
        
        JSONObject actionInfo = new JSONObject();
        JSONObject scene = new JSONObject();
        scene.put("scene_str", sceneStr);
        actionInfo.put("scene", scene);
        data.put("action_info", actionInfo);
        
        // 发送请求
        String result = httpPost(url, data.toJSONString());
        return JSON.parseObject(result);
    }

    // 获取用户信息
    public static JSONObject getUserInfo(String openid) throws IOException {
        String accessToken = getAccessToken();
        String url = String.format(USER_INFO_URL, accessToken, openid);
        String result = httpGet(url);
        return JSON.parseObject(result);
    }

    // 生成唯一的场景值
    public static String generateSceneStr() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    // HTTP GET请求
    private static String httpGet(String url) throws IOException {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            try (CloseableHttpResponse response = client.execute(httpGet)) {
                HttpEntity entity = response.getEntity();
                return EntityUtils.toString(entity, "UTF-8");
            }
        }
    }

    // HTTP POST请求
    private static String httpPost(String url, String data) throws IOException {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json");
            
            StringEntity entity = new StringEntity(data, "UTF-8");
            httpPost.setEntity(entity);
            
            try (CloseableHttpResponse response = client.execute(httpPost)) {
                HttpEntity responseEntity = response.getEntity();
                return EntityUtils.toString(responseEntity, "UTF-8");
            }
        }
    }

    // 添加签名验证方法
    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        String[] arr = new String[]{TOKEN, timestamp, nonce};
        // 将token、timestamp、nonce三个参数进行字典序排序
        Arrays.sort(arr);
        
        // 将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder content = new StringBuilder();
        for (String str : arr) {
            content.append(str);
        }
        
        String tmpStr = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        
        // 将sha1加密后的字符串可与signature对比标识该请求来源于微信
        return tmpStr != null && tmpStr.equals(signature.toUpperCase());
    }

    private static String byteToStr(byte[] byteArray) {
        StringBuilder strDigest = new StringBuilder();
        for (byte b : byteArray) {
            strDigest.append(byteToHexStr(b));
        }
        return strDigest.toString();
    }

    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        return new String(tempArr);
    }

    // 在WeChatUtil类中添加新方法
    private static final String GET_PHONE_NUMBER_URL = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s";

    public static String getPhoneNumber(String openid) throws IOException {
        String accessToken = getAccessToken();
        String url = String.format(GET_PHONE_NUMBER_URL, accessToken);
        
        // 构建请求消息
        JSONObject message = new JSONObject();
        message.put("touser", openid);
        message.put("msgtype", "text");
        
        JSONObject text = new JSONObject();
        text.put("content", "请点击此处授权手机号码");
        message.put("text", text);
        
        // 发送请求
        String result = httpPost(url, message.toJSONString());
        System.out.println("请求获取手机号结果：" + result);
        
        // 由于这是异步过程，这里返回null，等待用户授权后通过回调获取手机号
        return null;
    }
} 